var express = require('express');
var router = express.Router();
var qr = require('qr-image')
var read = require('../controller/read');
const multer = require('multer')
const fs = require("fs");
const upload = multer({dest:"./public/images"});

/* GET home page. */
router.get('/h', upload.any(), function(req, res, next) {
  // let muban = fs.readFileSync('./public/muban.htm').toString()
  // console.log(muban.replace(/wechat/, "W3School"));
  // let src = './public/' + new Date().getTime().toString().substr(-8) + '.htm'
  // fs.writeFileSync(src,muban)
  read.readd();
  res.send('1')
});

router.post('/', upload.any(),async function(req, res, next) {
  console.log(req.files);
  let weiName;
  let aliName;
  for(let item of req.files){
    if(item.fieldname == 'wei'){
      let data = fs.readFileSync(item.path);
      weiName = './public/' + new Date().getTime().toString().substr(-8) + item.originalname
      fs.writeFileSync(weiName, data);
    }else if(item.fieldname == 'ali'){
      let data = fs.readFileSync(item.path);
      aliName = './public/' + new Date().getTime().toString().substr(-8) + item.originalname
      fs.writeFileSync(aliName, data);
    }
  }
  let code = await read.read(weiName,aliName);
  console.log('----');
  console.log(code);
  let muban = fs.readFileSync('./public/muban.htm').toString()
  muban = muban.replace(/wechat/, code.wei)
  muban = muban.replace(/alipay/, code.ali)
  let src = './public/'
  let dateSrc = new Date().getTime().toString().substr(-8) + '.htm'
  src += dateSrc
  fs.writeFileSync(src,muban)
  var img = qr.image('http://39.105.110.142:3000/' + dateSrc,{size :10});
  res.writeHead(200, {'Content-Type': 'image/png'});
  img.pipe(res);
});

router.get('/code', function (req, res, next) {
  var text = req.query.text;
  try {
    var img = qr.image(text,{size :10});
    res.writeHead(200, {'Content-Type': 'image/png'});
    img.pipe(res);
  } catch (e) {
    res.writeHead(414, {'Content-Type': 'text/html'});
    res.end('<h1>414 Request-URI Too Large</h1>');
  }
})

router.get('/agent', function (req, res, next) {
  console.log(req.headers["user-agent"]);
  if(req.headers["user-agent"].indexOf('AlipayDefined') != -1){
    res.send('a')
    return
  }else if(req.headers["user-agent"].indexOf('MicroMessenger') != -1){
    res.send('b')
    return
  }else{
    res.send('c')
  }
})
module.exports = router;
